<?php
class Ogloszenia extends AppModel {
	var $name = 'Ogloszenia';
	var $displayField = 'name';
	
	var $virtualFields = array(
		'search' => 'Ogloszenia.name || Ogloszenia.content || Ogloszenia.tags'
	);
	
	public $actsAs = array('Searchable');
	
	public $filterArgs = array(
		array('name' => 'group_id', 'type' => 'subquery', 'method' => 'findByGroup', 'field' => 'Ogloszenia.id'),
		array('name' => 'search', 'type' => 'query', 'method' => 'orConditions')
	);
	
	var $validate = array(
		'name' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				'message' => 'Pole nie może być puste',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'unique' => array(
				'rule' => 'isUnique',
		        'message' => 'This name has already been taken.'
	        )
		),
		'user_id' => array(
			'numeric' => array(
				'rule' => array('numeric'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
	);
	//The Associations below have been created with all possible keys, those that are not needed can be removed

	var $belongsTo = array(
		'User' => array(
			'className' => 'User',
			'foreignKey' => 'user_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		)
	);

	var $hasAndBelongsToMany = array(
		'Group' => array(
			'className' => 'Group',
			'joinTable' => 'ogloszenia_groups',
			'foreignKey' => 'ogloszenia_id',
			'associationForeignKey' => 'group_id',
			'unique' => true,
			'conditions' => '',
			'fields' => '',
			'order' => '',
			'limit' => '',
			'offset' => '',
			'finderQuery' => '',
			'deleteQuery' => '',
			'insertQuery' => ''
		)
	);
	
	public function findByGroup($data = array()) {
		$this->OgloszeniaGroup->Behaviors->attach('Containable', array('autoFields' => false));
		$this->OgloszeniaGroup->Behaviors->attach('Search.Searchable');
		$query = $this->OgloszeniaGroup->getQuery('all', array(
	            'conditions' => array('OgloszeniaGroup.group_id'  => $data['group_id']),
	            'fields' => array('ogloszenia_id'),
	            'contain' => array()
		));
		return $query;
	}
	
	public function orConditions($data = array()){
		$aSearch = explode(' ',$data['search']);
		// szukana fraza
		$or = array($this->alias . '.search LIKE' => '%' . $data['search'] . '%');
		// szukana fraza rozbita na fragmenty
		if(is_array($aSearch)){
			foreach ($aSearch as $value) {				
				array_push($or,array($this->alias . '.search LIKE' => '%' . $value . '%') );
			}
		}

        $cond = array('OR' => $or);
        return $cond;
	}

}
